package com.example.administrator.im.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import android.transition.Fade;
import android.transition.Slide;
import android.transition.Transition;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.im.MyApplication;
import com.example.administrator.im.R;
import com.example.administrator.im.config.ImageConfig;
import com.example.administrator.im.config.ShareConfig;
import com.example.administrator.im.db.UserDBHelper;
import com.example.administrator.im.ui.activity.CalendarActivity;
import com.example.administrator.im.ui.activity.PersonalActivity;
import com.example.administrator.im.ui.activity.SettingActivity;
import com.example.administrator.im.ui.activity.WeatherActivity;
import com.example.administrator.im.utils.DownloadImageUtils;
import com.example.administrator.im.utils.FileUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.example.administrator.weather.gson.Weather;
import com.example.administrator.weather.utils.WeatherHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.io.File;
import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * create:2018/9/14 22:19
 * author: 姚鸿杰
 **/
public class MyFragment extends Fragment implements View.OnClickListener {

    private final String TAG = "MyFragment";

    private Context mContext;

    private ViewGroup vg;
    private ImageView setting;
    private LinearLayout civ_head_img;
    private TextView tv_nickname;
    private TextView tv_username;

    private CircleImageView head_img;

    private ViewGroup vg_weather;
    private ViewGroup vg_calendar;

    private TextView temperature;
    private TextView situation;
    private TextView street;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_my, container, false);

        mContext = getActivity();
        initView(v);

        EventBus.getDefault().register(this);
        return v;
    }

    private void initView(View v) {
        setting = (ImageView) v.findViewById(R.id.setting);
        setting.setOnClickListener(this);

        civ_head_img = (LinearLayout) v.findViewById(R.id.b_img);
        civ_head_img.setOnClickListener(this);

        vg = (ViewGroup) v.findViewById(R.id.bgd);
        tv_nickname = (TextView) v.findViewById(R.id.textView6);
        tv_username = (TextView) v.findViewById(R.id.textView7);

        head_img = (CircleImageView) v.findViewById(R.id.head_img);

        vg_weather = (ViewGroup) v.findViewById(R.id.weather);
        vg_weather.setOnClickListener(this);

        vg_calendar = (ViewGroup) v.findViewById(R.id.calendar);
        vg_calendar.setOnClickListener(this);

        temperature = (TextView) v.findViewById(R.id.textView2);
        situation = (TextView) v.findViewById(R.id.textView8);
        street = (TextView) v.findViewById(R.id.textView9);

        SharedPreferences spf = getContext().getSharedPreferences("weather", Context.MODE_PRIVATE);
        String content = spf.getString("content", "");
        if (!TextUtils.isEmpty(content)) {
            Weather weather = WeatherHttpUtils.handleWeatherResponse(content);
            String street = spf.getString("street", weather.basic.cityName);
            updateUI(new UpdateWeather(weather, street));
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        SharedPreferences spf = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String username = spf.getString("username", "");

        UserDBHelper user = LitePal.where("username = ?", username).findFirst(UserDBHelper.class);
        if (user == null)
            return;
        tv_username.setText(user.getUsername());
        tv_nickname.setText(user.getNickname());

        String url = HttpUtils.PORT + user.getImg_path();
        if (TextUtils.equals(url, HttpUtils.PORT)) {
            return;
        }
//        RequestOptions options = new RequestOptions()
//                .placeholder(R.mipmap.login_logo)
//                .error(R.mipmap.login_logo)
//                .override(120, 120);
//        Glide.with(mContext).load(url).apply(options).into(head_img);

        mFile = FileUtils.getFilePath(username, FileUtils.USER_PACK);

        saveImage(url, mFile, ImageConfig.getMyImage());
    }

    private File mFile;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Bitmap bitmap = (Bitmap) msg.obj;
            head_img.setImageBitmap(bitmap);
        }
    };

    private void saveImage(String url, File file, int size) {
        if (!file.exists()) {
            DownloadImageUtils downloadImage = new DownloadImageUtils(url, MyApplication.getmContext(),
                    size, size, file, new DownloadImageUtils.ImagedownLoadCallBack() {
                @Override
                public void onDownLoadSuccess(final File file) {
                    Message msg = new Message();
                    Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                }

                @Override
                public void onDownLoadFailed() {
                }
            });
            new Thread(downloadImage).start();
        } else {
            head_img.setImageBitmap(BitmapFactory.decodeFile(file.getPath()));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting:
                Intent setting = new Intent(getActivity(), SettingActivity.class);
                mContext.startActivity(setting);
                break;
            case R.id.b_img:

                if (ShareConfig.isExist()) {
                    ShareConfig shareConfig = ShareConfig.getInstance();
//                    int vg_height = vg.getHeight();
                    shareConfig.setVg_width(v.getLeft());
                    shareConfig.setVg_height(v.getTop());

                    shareConfig.setImg_width(v.getWidth());
                    shareConfig.setImg_height(v.getHeight());

                    int tv_width = tv_nickname.getLeft();
                    int tv_height = tv_nickname.getTop();
                    shareConfig.setTv_widht(tv_width);
                    shareConfig.setTv_height(tv_height);
                }

                Intent personal = new Intent(getActivity(), PersonalActivity.class);
                personal.putExtra("headImg", mFile.getPath());

                Pair<View, String> pair1 = new Pair<View, String>(tv_nickname, "nickname");
                Pair<View, String> pair2 = new Pair<View, String>(vg, "bgd");
                Pair<View, String> pair3 = new Pair<View, String>(head_img, "headimg");
//                Pair<View, String> pair2 = new Pair<View, String>(textView, getString(R.string.shareElement_txt));
                // 这里指定了共享的视图元素
                ActivityOptionsCompat options = ActivityOptionsCompat
                        .makeSceneTransitionAnimation(getActivity(), pair1, pair2, pair3);
                ActivityCompat.startActivity(getActivity(), personal, options.toBundle());


//                mContext.startActivity(personal);
                break;
            case R.id.weather:
                Intent weather = new Intent(getActivity(), WeatherActivity.class);
                mContext.startActivity(weather);
                break;
            case R.id.calendar:
                Intent calendar = new Intent(getActivity(), CalendarActivity.class);
                mContext.startActivity(calendar);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateWeather(UpdateWeather weather) {
        updateUI(weather);
    }

    private void updateUI(UpdateWeather weather) {
        temperature.setText(weather.weather.now.temperature);
        situation.setText(weather.weather.now.more.info);
        street.setText(weather.getStreet());
    }

    public static class UpdateWeather {
        private Weather weather;

        private String street;

        public String getStreet() {
            return street;
        }

        public UpdateWeather(Weather weather, String street) {

            this.weather = weather;
            this.street = street;
        }

        public UpdateWeather(Weather weather) {
            this.weather = weather;
        }

        public Weather getWeather() {
            return weather;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
